﻿using System.IO;
using Prism.Events;
using System.Text.Json;
using System.Windows;
using Microsoft.Web.WebView2.Core;
using SoonCode.Core;
using SoonCode.FocusTest.Events;
using SoonCode.FocusTest.Models;

namespace SoonCode.FocusTest.Views
{
    /// <summary>
    /// WebBrowser.xaml 的交互逻辑
    /// </summary>
    public partial class WebBrowser : BaseWindow
    {
        private IEventAggregator _aggregator;
        public WebBrowser(IEventAggregator aggregator)
        {
            InitializeComponent();
            _aggregator = aggregator;
            Closing += WebBrowser_Closing;
            initWebView();
        }

        private void WebBrowser_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
            this._aggregator.GetEvent<OpenPageEvent>().Publish(new WebAppModel(){url="about:blank",title = ""});
        }

        private async void initWebView()
        {
            await WebView2.EnsureCoreWebView2Async();
            var profile = WebView2.CoreWebView2.Profile;
            await profile.ClearBrowsingDataAsync();
            WebView2.NavigationCompleted += WebView2_NavigationCompleted;
            WebView2.NavigationStarting += WebView2_NavigationStarting;
            WebView2.CoreWebView2.Settings.AreDevToolsEnabled = false;
            WebView2.CoreWebView2.ContextMenuRequested+= (o,e) => e.Handled=true;
        }

        private void WebView2_NavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e)
        {
            if (e.Uri.Contains("http://print/"))
            {
                e.Cancel = true;
                string c = e.Uri.Substring(e.Uri.IndexOf("parm=") + 5);
                c=c.Base64Decode();
                Dictionary<string,object> dict= JsonSerializer.Deserialize<Dictionary<string, object>>(c);
                TestPrintModel model = new TestPrintModel();
                model.Age = dict["age"].ToString();
                model.Name = dict["name"].ToString();
                model.Sex = dict["sex"].ToString();
                model.AvgScore = dict["averageScore"].ToString();
                model.PID = dict["pid"].ToString();
                model.TestDate = dict["testtime"].ToString();
                for (int i = 1; i <= 9; i++)
                {
                    string[] val = dict["score" + i].ToString().Split(":");
                    model.ScoreList.Add(new ScoreModel() { Name = val[0], Score = val[1] });
                }
                EventInfo info = new EventInfo();
                info.Type = TestPrintModel.type;
                info.Data["model"] = model;
                this._aggregator.GetEvent<PrintTestResultEvent>().Publish(info);
            }else if (e.Uri.Contains("http://printsensory/"))
            {
                e.Cancel = true;
                string c = e.Uri.Substring(e.Uri.IndexOf("parm=") + 5);
                c = c.Base64Decode();
                Dictionary<string, object> dict = JsonSerializer.Deserialize<Dictionary<string, object>>(c);
                SensoryPrintModel model = new SensoryPrintModel();
                model.Age = dict["age"].ToString();
                model.Name = dict["name"].ToString();
                model.Sex = dict["sex"].ToString();
                model.AvgScore = dict["averageScore"].ToString();
                model.ID = dict["id"].ToString();
                model.TestDate = dict["testtime"].ToString();
                for (int i = 1; i <= 3; i++)
                {
                    string[] val = dict["score" + i].ToString().Split(":");
                    model.ScoreList.Add(new ScoreModel() { Name = val[0], Score = val[1] });
                }
                EventInfo info = new EventInfo();
                info.Type = SensoryPrintModel.type;
                info.Data["model"] = model;
                this._aggregator.GetEvent<PrintTestResultEvent>().Publish(info);
            }
            LoadingCircle.Visibility= Visibility.Collapsed;
        }

        private void WebView2_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            LoadingCircle.Visibility = Visibility.Hidden;
        }

        private void CloseButton_OnClick(object sender, RoutedEventArgs e)
        {   
            this.Close();
        }
    }
}
